package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import entities.Domain;

public class ConnectionHandle {

	public static Domain fetchDomainByUrlThroughURLConnection(String strUrl) {
		Domain domain = new Domain();
		try {
			URL url = new URL(strUrl);
			domain.setName(url.getHost());
			URLConnection yc = url.openConnection();
			yc.setRequestProperty("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			yc.setRequestProperty("Cache-Control", "max-age=0");
			yc.setRequestProperty("Connection", "keep-alive");
			yc.setReadTimeout(2000);
			yc.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0");
			BufferedReader in = new BufferedReader(new InputStreamReader(
					yc.getInputStream(), "UTF-8"));
			StringBuffer header = new StringBuffer();
			for (int i = 0;; i++) {
				String headerName = yc.getHeaderFieldKey(i);
				String headerValue = yc.getHeaderField(i);

				if (headerName == null && headerValue == null) {
					break;
				} else {
					header.append(headerName + ":" + headerValue + "\n");
				}
			}
			domain.setHeader(header.toString());
			StringBuffer html = new StringBuffer();
			String inputLine;
			while ((inputLine = in.readLine()) != null)
				html.append(inputLine + "\n");
			in.close();
			domain.setHtml(html.toString());

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return domain;
	}

	public static Domain fetchDomainByUrlThroughJsoup(String strUrl) {
		Domain domain = new Domain();
		try {
			Connection doc = Jsoup
					.connect(strUrl)
					.followRedirects(true)
					.timeout(10000)
					.referrer(strUrl)
					.header("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
					.header("User-Agent",
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0")
					.ignoreHttpErrors(true).ignoreContentType(true);
			Response response = doc.execute();
			domain.setHtml(doc.get().html());
			domain.setName(Utils.handleToBeGoodDomain(strUrl));
			StringBuffer buffer = new StringBuffer();
			for (Map.Entry<String, String> item : response.headers().entrySet()) {
				buffer.append(item.getKey() + ":" + item.getValue() + "\n");
			}
			buffer.append("Set-Cookie:");
			for (Map.Entry<String, String> item : response.cookies().entrySet()) {
				buffer.append(item.getKey() + "=" + item.getValue() + ", ");
			}
			domain.setHeader(buffer.toString());
			return domain;

		} catch (IOException e) {
			System.err.println(e.getMessage() + " - " + strUrl);
			return null;
		}
	}
}
